package utils

import (
	"fmt"
	"github.com/dop251/goja"
	"github.com/dop251/goja_nodejs/require"
	"reflect"
	"sync"
)

type SafeNativeModuleSlice struct {
	loaderFuncs map[string]func(runtime *goja.Runtime)
	sync.Mutex
}

func (p *SafeNativeModuleSlice) Add(nodes ...func(runtime *goja.Runtime)) {
	p.Lock()
	defer p.Unlock()
	if p.loaderFuncs == nil {
		p.loaderFuncs = make(map[string]func(runtime *goja.Runtime))
	}
	for _, node := range nodes {
		p.loaderFuncs[fmt.Sprintf("%s", reflect.ValueOf(node))] = node
	}
}

func (p *SafeNativeModuleSlice) Modules() map[string]func(runtime *goja.Runtime) {
	p.Lock()
	defer p.Unlock()
	return p.loaderFuncs
}

func (p *SafeNativeModuleSlice) ModuleLoader(vm *goja.Runtime, path ...string) {

	p.Lock()
	defer p.Unlock()

	var folder = ""
	if len(path) == 1 {
		folder = path[0]
	}

	if folder == "" {
		folder = `components`
	}

	registry := require.NewRegistry(
		require.WithGlobalFolders(folder),
		require.WithLoader(func(path string) ([]byte, error) {
			return ReadFile(path)
		}),
	)

	registry.Enable(vm)
	for _, f := range p.loaderFuncs {
		f(vm)
	}

}

var Registry = &SafeNativeModuleSlice{}
